package org.leiyang.common.config;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import reactor.core.publisher.Mono;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class ReactorHttpMessageConverter extends AbstractHttpMessageConverter<Mono<Object>> {

    public ReactorHttpMessageConverter(Charset defaultCharset){
        super(defaultCharset, MediaType.TEXT_PLAIN, MediaType.ALL);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected Mono<Object> readInternal(Class<? extends Mono<Object>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            InputStream inputStream = inputMessage.getBody();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String data = baos.toString();
            return Mono.just(data);
        }
    }

    @Override
    protected void writeInternal(Mono<Object> objectMono, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    }


}
